import { Component, OnInit, SecurityContext, TemplateRef } from '@angular/core';
import { Technologiy } from 'src/app/model/technology';
import { TypeaheadMatch } from 'ngx-bootstrap/typeahead/typeahead-match.class';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { DomSanitizer } from '@angular/platform-browser';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
import { BsModalService } from 'ngx-bootstrap/modal';
import { User } from 'src/app/model/user';
import { Trainings } from 'src/app/model/trainings';

@Component({
  selector: 'app-searchtrainings',
  templateUrl: './searchtrainings.component.html',
  styleUrls: ['./searchtrainings.component.css']
})
export class SearchtrainingsComponent implements OnInit {
  headers = new HttpHeaders({ 'Content-Type': 'application/json' });
  modalRef: BsModalRef

  minDate: Date = new Date()
  maxDate: Date = new Date()
  bsRangeValue: Date[]

  skills: string = ''
  skillsArray: string[] = []
  response: any
  list_user: User[]

  mentorId: number
  name: string
  proposal: string
  user: User
  trainings: Trainings

  constructor(private http: HttpClient,
    private modalService: BsModalService,
    sanitizer: DomSanitizer) {
    this.alerts = this.alerts.map((alert: any) => ({
      type: alert.type,
      msg: sanitizer.sanitize(SecurityContext.HTML, alert.msg)
    }))

    this.user = JSON.parse(localStorage.getItem('userinfo'))

    this.http.get('/api/technologies')
      .subscribe((data: any) => {
        console.log('/api/technologies', data)
        this.response = data;
        this.response.forEach(element => {
          this.technologies.push(element);
        })
        console.log('this.technologies', this.technologies)
      })

    this.minDate = new Date()
    let bsValue: Date = new Date()
    bsValue.setDate(this.minDate.getDate() + 7)
    this.maxDate = new Date()
    this.minDate.setDate(this.minDate.getDate())
    this.maxDate.setDate(this.minDate.getDate() + 365)
    this.bsRangeValue = [this.minDate, bsValue]
    console.log('2this.bsRangeValue', this.bsRangeValue)

    this.http.post<any>('/api/user/searchMentorByKey',
      { startDate: this.bsRangeValue[0], endDate: this.bsRangeValue[1], key: this.selectedValue },
      { headers: this.headers, reportProgress: true })
      .subscribe((data: any) => {
        console.log('/api/user/searchMentorByKey', data)
        if (data.status == 'success') {
          // alert(data.msg)
          this.list_user = data.data
        } else {
          alert(data.msg)
        }
      })
  }

  ngOnInit(): void {
  }

  openModal(template: TemplateRef<any>) {
    this.name = ''
    this.proposal = ''
    this.modalRef = this.modalService.show(template);
  }
  
  selectedValue: string
  selectedOption: any
  selectedOptions: any[] = []
  technologies: Technologiy[] = []
  alerts: any = []

  change(event: any): void {
    console.log('change')
    this.alerts = []
  }
  onSelect(event: TypeaheadMatch): void {
    var index = this.selectedOptions.findIndex(function (v) {
      return event.item.id === v.id;
    })
    if (index < 0) {
      this.selectedOption = event.item
      this.selectedOptions.push(event.item)
      this.skillsArray.push(event.item.name)
      this.skills = this.skillsArray.toString()
      console.log(this.skills)
      console.log(this.selectedOptions)
    } else {
      this.alerts = [
        {
          type: 'danger',
          msg: `<strong>Warning!</strong> You have selected this skill.`
        }
      ]
    }
  }

  search() {
    this.http.post<any>('/api/user/searchMentorByKey',
      { startDate: this.bsRangeValue[0], endDate: this.bsRangeValue[1], key: this.selectedValue },
      { headers: this.headers, reportProgress: true })
      .subscribe((data: any) => {
        console.log('/api/user/searchMentorByKey', data)
        if (data.status == 'success') {
          // alert(data.msg)
          this.list_user = data.data
        } else {
          alert(data.msg)
        }
      })
  }

  sendProposal(){
    console.log('sendProposal', this.proposal)
    console.log('sendProposal', this.user)
    this.trainings = new Trainings()
    this.trainings.userId = this.user.id
    this.trainings.mentorId = this.mentorId
    this.trainings.name = this.name
    this.trainings.proposal = this.proposal
    this.trainings.rate = 0
    this.trainings.trainingsStatus = 1
    console.log(this.trainings)
    this.http.post<any>('/api/trainings/add',
      this.trainings,
      { headers: this.headers, reportProgress: true })
      .subscribe((data: any) => {
        console.log(data)
        if (data.status == 'success') {
          setTimeout(() => {
            window.location.assign('/login')
          }, 1000);
        } else if (data.status == 'codefail') {
          alert('Captcha is wrong')
        }
      })
  }
}
